package com.sz.common.core.system.service.impl;

import com.sz.common.base.constants.UserActions;
import com.sz.common.base.dao.DaoSupport;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.TreeNode;
import com.sz.common.base.exception.BizException;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.i18n.I18nMessages;
import com.sz.common.base.utils.EntityUtils;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.base.utils.TreeBuilder;
import com.sz.common.core.service.PrincipalLogUtils;
import com.sz.common.core.service.role.MembershipType;
import com.sz.common.core.service.role.RoleMembership;
import com.sz.common.core.constants.SysErrorCodes;
import com.sz.common.core.constants.MessagesCodes;
import com.sz.common.core.constants.ModuleNames;
import com.sz.common.core.system.entity.Role;
import com.sz.common.core.system.entity.Org;
import com.sz.common.core.system.entity.OrgRole;
import com.sz.common.core.system.entity.UserOrg;
import com.sz.common.core.system.service.OrgService;
import com.sz.common.core.system.service.UserService;
import com.sz.common.core.system.dto.*;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Function: 组织机构 <br>
 * Author: wentao.chang <br>
 * Date: 2016-10-31 09:45:00
 */
@Service
public class OrgServiceImpl implements OrgService {

    public static final int ROOT = 0;
    public static final int PARENT_GROUP = 1;
    public static final String START_SPLIT = "##";
    public static final int ORG_DRAG_NAME_REPEAT = 1;
    public static final int USER_GROUP_DRAG_NAMEREPEAT = 2;
    public static final int GROUP = 2;
    public static final String REGEX = "##";
    @Resource(name = "daoSupport")
    private DaoSupport dao;

    /**
     * 保存单个组织
     *
     * @see OrgService#saveOrg(int, OrgDto)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int saveOrg(int orgGroupId, OrgDto orgDto) {
        // 组织机构只允许一个父节点
        if (orgGroupId == 1 && orgDto.getParentId() == 0) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_ARGUMENT_ILLEGAL, "orgGroupId=1&parentId=0");
        }

        checkDataValid(orgDto);
        Org org = new Org();
        BeanUtils.copyProperties(orgDto, org);
        org.setIsDeleted(false);
        org.setOrgGroupId(orgGroupId);
        checkOrgExist(org);

        Org porg = (Org) dao.findForObject("OrgMapper.findById", org.getParentId());
        if (porg != null) {
            org.setLongCode(porg.getLongCode() + "##" + org.getCode());
            org.setLevel(porg.getLevel() + 1);
        } else {
            org.setLongCode(org.getCode());
            org.setLevel(1);
        }
        List<Org> sameLevelOrgs = getSubOrgs(org.getOrgGroupId(), org.getParentId());

        if (sameLevelOrgs != null && sameLevelOrgs.size() > 0) {
            org.setOrdinal(sameLevelOrgs.size() + 1);
        } else {
            org.setOrdinal(1);
        }
        org.setIsLeaf(true);
        dao.save("OrgMapper.insert", org);
        // 将父节点的Leaf置为false
        if (porg != null) {
            porg.setIsLeaf(false);
            dao.update("OrgMapper.update", porg);
        }
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("ADD_ORG", orgDto);
        String log = String.format((orgGroupId != 2 ? "新建组织" : "新建用户组"));
        PrincipalLogUtils.addOperationLog(ModuleNames.SYS, ModuleNames.SYS_ORG, UserActions.ADD, log, dataBackup);
        return org.getId();
    }

    private void checkDataValid(OrgDto orgDto) {
        if (orgDto.getShortName() != null) {
            orgDto.setShortName(orgDto.getShortName().trim());
        }
        if (StringUtils.isEmpty(orgDto.getShortName())) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_ARGUMENT_EMPTY, "shortName");
        }

        if (orgDto.getCode() != null) {
            orgDto.setCode(orgDto.getCode().trim());
        }
        if (StringUtils.isEmpty(orgDto.getCode())) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_ARGUMENT_EMPTY, "code");
        }

        if (orgDto.getName() != null) {
            orgDto.setName(orgDto.getName().trim());
        }
        if (StringUtils.isEmpty(orgDto.getName())) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_ARGUMENT_EMPTY, "name");
        }
    }

    /**
     * 更新单个组织
     *
     * @see OrgService#updateOrg(int, int, OrgDto)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateOrg(int orgGroupId, int orgId, OrgDto orgDto) {
        // 组织机构只允许一个父节点
        if (orgGroupId == 1 && orgDto.getParentId() == 0 && orgId != 1) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_ARGUMENT_ILLEGAL, "orgGroupId=1&parentId=0");
        }

        checkDataValid(orgDto);
        Org org = (Org) dao.findForObject("OrgMapper.findById", orgId);
        if (org == null) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NOT_FOUND, orgId);
        }

        if (org.getIsSystem()) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_ISSYSTEM_NOEDIT, "");
        }
        if (org.getOrgGroupId() != orgGroupId) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NOT_FOUND,
                    "orgGroupId:" + org.getOrgGroupId() + "~" + "org.getOrgGroupId:" + org.getOrgGroupId());
        }
        // 批量更新用
        String originalCode = org.getCode();
        String originalLongCode = org.getLongCode();
        final boolean orgCodeChanged = !originalCode.equals(orgDto.getCode());
        // 设置字段值
        org.setDescription(orgDto.getDescription());
        org.setCode(orgDto.getCode());
        org.setName(orgDto.getName());
        org.setShortName(orgDto.getShortName());
        org.setParentId(orgDto.getParentId());

        checkOrgExist(org);

        Org porg = (Org) dao.findForObject("OrgMapper.findById", org.getParentId());
        if (porg != null) {
            org.setLongCode(porg.getLongCode() + "##" + org.getCode());
        } else {
            org.setLongCode(org.getCode());
        }

        Map<Integer, Org> orgMap = new HashMap<>();
        orgMap.put(org.getId(), org);
        // 如果编码发生改变 批量更新子节点的长编码
        if (orgCodeChanged) {
            List<Org> subOrgs = getAllSubOrgsByLongCode(orgGroupId, originalLongCode);
            if (subOrgs != null) {
                for (Org subOrg : subOrgs) {
                    subOrg.setLongCode(
                            orgMap.get(subOrg.getParentId()).getLongCode() + "##" + subOrg.getCode());
                    orgMap.put(subOrg.getId(), subOrg);
                }
                batchUpdateOrg(subOrgs);
            }
        }
        dao.update("OrgMapper.update", org);
        // 将父节点的Leaf置为false
        if (porg != null) {
            porg.setIsLeaf(false);
            dao.update("OrgMapper.update", porg);
        }
        //添加要更新数据的日志信息
        Map<String, Object> dataBackup = new HashMap<>();
        orgDto.setId(orgId);
        dataBackup.put("UPDATE_ORG", orgDto);
        String log = String.format((orgGroupId != 2 ? "修改组织" : "修改用户组"));
        PrincipalLogUtils.addOperationLog(ModuleNames.SYS, ModuleNames.SYS_ORG, UserActions.UPDATE, log, dataBackup);
    }

    /**
     * 批量更新组织。
     *
     * @param orgs 组织
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void batchUpdateOrg(List<Org> orgs) {
        if (orgs.size() == 0) {
            return;
        }
        dao.batchUpdate("OrgMapper.update", orgs);
        if (orgs.get(0).getOrgGroupId() == 1) {
            List<Org> onlyoneroot = getSubOrgs(1, 0);
            if (onlyoneroot.size() != 1) {
                throw new BizException(-1, "此操作引起了两个根节点！！！！");
            }
        }
        //添加要更新数据的日志信息
        //Map<String, Object> dataBackup = new HashMap<>();
        //dataBackup.put("BATCH_UPDATE_ORG", orgs);
        //PrincipalLogUtils.addOperationLog(ModuleNames.SYS, ModuleNames.SYS_ORG, UserActions.UPDATE, "批量修改组织", dataBackup);
    }

    private void checkOrgExist(Org org) {
        String module;
        if (org.getOrgGroupId() == 1) {
            module = MessagesCodes.MODULE_ORG;
        } else {
            module = MessagesCodes.MODULE_USER_GROUP;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orgGroupId", org.getOrgGroupId());
        map.put("code", org.getCode());
        map.put("id", org.getId());

        List<Org> orgs = dao.findForList("OrgMapper.findOrgByOrgCode", map, Org.class);
        if (orgs.size() > 0) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_CODE_EXIST, getModuleName(module)[0]);
        }

        //下面的是校验同级的
        map = new HashMap<>();
        map.put("orgGroupId", org.getOrgGroupId());
        map.put("name", org.getName());
        map.put("parentId", org.getParentId());
        map.put("id", org.getId());
        orgs = dao.findForList("OrgMapper.findOrgByOrgName", map, Org.class);
        if (orgs.size() > 0) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NAME_EXIST, getModuleName(module)[0]);
        }
        map = new HashMap<>();
        map.put("orgGroupId", org.getOrgGroupId());
        map.put("parentId", org.getParentId());
        map.put("shortName", org.getShortName());
        map.put("id", org.getId());
        orgs = dao.findForList("OrgMapper.findOrgByOrgShortName", map, Org.class);
        if (orgs.size() > 0) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_SHORTNAME_EXIST, getModuleName(module)[0]);
        }

        // 跟父亲不能重名
        Org porg = (Org) dao.findForObject("OrgMapper.findById", org.getParentId());
        checkOrgName(org, porg, module);
        // 跟所有儿子不能重名
        if (org.getId() > 0) {
            List<Org> childrenOrgs = getSubOrgs(org.getOrgGroupId(), org.getId());
            for (Org childrenOrg : childrenOrgs) {
                checkOrgName(org, childrenOrg, module);
            }
        }
    }

    private void checkOrgName(Org org, Org compareOrg, String module) {
        if (compareOrg != null) {
            if (compareOrg.getShortName().equals(org.getShortName())) {
                throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_SHORTNAME_EXIST, getModuleName(module)[0]);
            }
            if (compareOrg.getName().equals(org.getName())) {
                throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NAME_EXIST, getModuleName(module)[0]);
            }
        }
    }

    /**
     * 获取子级节点的Dto
     *
     * @see OrgService#getSubOrgDtos(int, int)
     */
    @Override
    public List<TreeNode> getSubOrgDtos(int orgGroupId, int parentid) {
        List<Org> suborgs = getSubOrgs(orgGroupId, parentid);
        List<TreeNode> nodes = new ArrayList<>();
        setListData(orgGroupId, suborgs, nodes);
        return nodes;
    }

    /**
     * 按parentId查询子级节点 按order序
     *
     * @see OrgService#getSubOrgs(int, int)
     */
    @Override
    public List<Org> getSubOrgs(int orgGroupId, int parentid) {

        Map<String, Object> map = new HashMap<>();
        map.put("orgGroupId", orgGroupId);
        map.put("parentId", parentid);

        return dao.findForList("OrgMapper.getSubOrgs", map, Org.class);
    }

    /**
     * 查询树结构 支持关键字查询
     *
     * @see OrgService#getOrgTreeByOrgGroupId(int, java.lang.String)
     */
    @Override
    public List<TreeNode> getOrgTreeByOrgGroupId(int orgGroupId, String q) {
        Map<String, Object> map = new HashMap<>();
        map.put("orgGroupId", orgGroupId);
        map.put("q", StringUtils.replaceSqlPattern(q));

        List<Org> orgs = dao.findForList("OrgMapper.getOrgByFilter", map, Org.class);
        if (orgs != null && orgs.size() > 0) {

            List<TreeNode> nodes = new ArrayList<>();
            setListData(orgGroupId, orgs, nodes);

            Map<String, String> codes = getOrgCodeMap(orgs);
            Object[] longcodes = codes.keySet().toArray();
            map = new HashMap<>();
            map.put("orgGroupId", orgGroupId);
            map.put("array", longcodes);
            List<Org> porgs = dao.findForList("OrgMapper.findOrgByOrgCodes", map, Org.class);
            Map<String, Org> porgMap = EntityUtils.getStringKeyMapFromBeans(porgs, "id");
            for (TreeNode node : nodes) {

                // 设置父节点
                Org porg = porgMap.get(node.getParentId() + "");
                while (porg != null) {
                    node.getParentIds().add(0, porg.getId());
                    porg = porgMap.get(porg.getParentId() + "");
                }
            }

            return TreeBuilder.buildListToTree(nodes);
        }

        return null;
    }

    private Map<String, String> getOrgCodeMap(List<Org> orgs) {
        Map<String, String> codes = new HashMap<>();
        for (Org org : orgs) {
            String[] longcodes = org.getLongCode().split("##");
            for (String longcode : longcodes) {
                if (!codes.containsKey(longcode)) {
                    codes.put(longcode, longcode);
                }
            }
        }
        return codes;
    }

    /**
     * 获取组织列表 查询关键字
     *
     * @see OrgService#getOrgListByOrgGroupId(int,
     * java.lang.String, int)
     */
    @Override
    public List<OrgDto> getOrgListByOrgGroupId(int orgGroupId, String q, int porgid) {
        if (StringUtils.isEmpty(q)) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orgGroupId", orgGroupId);
        map.put("q", StringUtils.replaceSqlPattern(q));
        Org parentOrg = (Org) dao.findForObject("OrgMapper.findById", porgid);
        if (parentOrg != null) {
            map.put("porgLongCode", parentOrg.getLongCode());
        } else {
            map.put("porgLongCode", null);
        }
        List<Org> orgs = dao.findForList("OrgMapper.getOrgByFilter", map, Org.class);

        List<OrgDto> dtos = new ArrayList<>();
        if (orgs != null && orgs.size() > 0) {
            Map<String, String> codes = getOrgCodeMap(orgs);
            Object[] longcodes = codes.keySet().toArray();
            map = new HashMap<>();
            map.put("orgGroupId", orgGroupId);
            map.put("array", longcodes);
            List<Org> porgs = dao.findForList("OrgMapper.findOrgByOrgCodes", map, Org.class);
            Map<String, Org> porgMap = EntityUtils.getStringKeyMapFromBeans(porgs, "id");
            for (Org org : orgs) {
                OrgDto dto = new OrgDto();
                BeanUtils.copyProperties(org, dto);
                dto.setIsLeaf(org.getIsLeaf());
                // 设置父节点
                Org porg = porgMap.get(org.getParentId() + "");
                while (porg != null) {
                    dto.getParentIds().add(0, porg.getId());
                    porg = porgMap.get(porg.getParentId() + "");
                }
                dtos.add(dto);
            }
        }
        return dtos;

    }

    /**
     * 检查组织编码
     *
     * @param orgGroupId
     * @param orgId
     * @param code
     * @return
     */
    @Override
    public void orgCodeCheck(int orgGroupId, int orgId, String code) {
        String module;
        if (orgGroupId == 1) {
            module = MessagesCodes.MODULE_ORG;
        } else {
            module = MessagesCodes.MODULE_USER_GROUP;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orgGroupId", orgGroupId);
        map.put("code", code);
        map.put("id", orgId);

        List<Org> orgs = dao.findForList("OrgMapper.findOrgByOrgCode", map, Org.class);
        if (orgs.size() > 0) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_CODE_EXIST, getModuleName(module)[0]);
        }
    }

    /**
     * 检查组织名称
     *
     * @param orgGroupId
     * @param orgGroupId
     * @param orgId
     * @param name
     * @return
     */
    @Override
    public void orgNameCheck(int orgGroupId, int parentId, int orgId, String name) {
        String module;
        if (orgGroupId == 1) {
            module = MessagesCodes.MODULE_ORG;
        } else {
            module = MessagesCodes.MODULE_USER_GROUP;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orgGroupId", orgGroupId);
        map.put("name", name);
        map.put("parentId", parentId);
        map.put("id", orgId);
        List<Org> orgs = dao.findForList("OrgMapper.findOrgByOrgName", map, Org.class);
        if (orgs.size() > 0) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NAME_EXIST, getModuleName(module)[0]);
        }


        // 跟父亲不能重名
        if (parentId != 0) {
            Org porg = (Org) dao.findForObject("OrgMapper.findById", parentId);
            if (name.equals(porg.getName())) {
                throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NAME_EXIST, getModuleName(module)[0]);
            }
        }


        //与子不能重名
        if (orgId > 0) {
            List<Org> childrenOrgs = getSubOrgs(orgGroupId, orgId);
            for (Org childrenOrg : childrenOrgs) {
                if (name.equals(childrenOrg.getName())) {
                    throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NAME_EXIST, getModuleName(module)[0]);
                }

            }
        }
    }

    /**
     * 检查组织简称
     *
     * @param orgGroupId
     * @param parentId
     * @param orgId
     * @param shortName
     * @return
     */
    @Override
    public void orgShortNameCheck(int orgGroupId, int parentId, int orgId, String shortName) {
        String module;
        if (orgGroupId == 1) {
            module = MessagesCodes.MODULE_ORG;
        } else {
            module = MessagesCodes.MODULE_USER_GROUP;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("orgGroupId", orgGroupId);
        map.put("parentId", parentId);
        map.put("shortName", shortName);
        map.put("id", orgId);
        List<Org> orgs = dao.findForList("OrgMapper.findOrgByOrgShortName", map, Org.class);
        if (orgs.size() > 0) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_SHORTNAME_EXIST, getModuleName(module)[0]);
        }

        // 跟父亲不能重名
        if (parentId != 0) {
            Org porg = (Org) dao.findForObject("OrgMapper.findById", parentId);
            if (shortName.equals(porg.getShortName())) {
                throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_SHORTNAME_EXIST, getModuleName(module)[0]);
            }
        }
        //与子不能重名
        if (orgId > 0) {
            List<Org> childrenOrgs = getSubOrgs(orgGroupId, orgId);
            for (Org childrenOrg : childrenOrgs) {
                if (shortName.equals(childrenOrg.getShortName())) {
                    throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_SHORTNAME_EXIST, getModuleName(module)[0]);
                }
            }
        }
    }

    /**
     * 设置用户数
     *
     * @param orgGroupId orgGroupId
     * @param orgs       orgs
     * @param nodes      nodes
     */
    private void setListData(int orgGroupId, List<Org> orgs, List<TreeNode> nodes) {
        if (orgs == null || orgs.size() == 0) {
            return;
        }

        List<OrgUserCountDto> orgUserCountDtos = dao.findForList("UserOrgMapper.queryAllUserOrgListByOrgGroupId",
                orgGroupId, OrgUserCountDto.class);
        for (Org org : orgs) {
            OrgTreeNode treeNode = new OrgTreeNode();
            treeNode.setId(org.getId());
            treeNode.setName(org.getName());
            treeNode.setOrgShortName(org.getShortName());
            treeNode.setOrgCode(org.getCode());
            treeNode.setParentId(org.getParentId());
            treeNode.setLeaf(org.getIsLeaf());
            treeNode.setIsSystem(org.getIsSystem());
            //循环计算人数
            Map<String, String> hasCnt = new HashMap<>();
            for (OrgUserCountDto oucDto : orgUserCountDtos) {
                if (isSubNode(org, oucDto) && hasCnt.get(oucDto.getUserId() + "") == null) {
                    treeNode.setUserCount(treeNode.getUserCount() + oucDto.getUserCount());
                    hasCnt.put(oucDto.getUserId() + "", "-");
                }
            }
            nodes.add(treeNode);
        }
    }

    private boolean isSubNode(Org porg, OrgUserCountDto suborg) {
        if (porg.getLongCode().equals(suborg.getLongCode())) {
            return true;
        }
        return suborg.getLongCode().startsWith(porg.getLongCode() + "##");
    }

    /**
     * 按长编码查询子级所有的节点 按层级以及order排序 不包含longCode节点本身
     *
     * @see OrgService#getAllSubOrgsByLongCode(int,
     * java.lang.String)
     */

    @Override
    public List<Org> getAllSubOrgsByLongCode(int orgGroupId, String orgLongCode) {
        Map<String, Object> map = new HashMap<>();
        map.put("orgGroupId", orgGroupId);
        map.put("longCode", orgLongCode);
        return dao.findForList("OrgMapper.getAllSubOrgsByLongCode", map, Org.class);
    }

    /**
     * 比如要把一个节点orgid拖动到节点A后面 则下面方法的参数如下所示,<br>
     * 如果拖动到目标层的第一个元素，则targetPreId为0<br>
     * <p>
     * <p>
     * <pre>
     * ---+目标层【targetParentId】
     *    |-----目标层子节点A【targetPreId】
     *    |-----目标层子节点B
     * </pre>
     *
     * @see OrgService#dragOrgTree(int, int,
     * int, int)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void dragOrgTree(int orgGroupId, int orgid, int targetParentId, int targetPreId) {
        // 组织机构父节点不允许拖动
        if (orgGroupId == PARENT_GROUP && targetParentId == ROOT) {
            return;
        }
        // 拖动到的目标层的
        Org targetParentOrg = (Org) dao.findForObject("OrgMapper.findById", targetParentId);
        if (orgGroupId == PARENT_GROUP && targetParentId != ROOT) {
            if (targetParentOrg == null || orgGroupId != targetParentOrg.getOrgGroupId()) {
                throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NOT_FOUND,
                        "orgGroupId:" + orgGroupId + "~" + targetParentId);
            }
        }
        // 被拖动的节点
        Org dragedOrg = (Org) dao.findForObject("OrgMapper.findById", orgid);
        if (dragedOrg == null || orgGroupId != dragedOrg.getOrgGroupId()) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NOT_FOUND, orgid);
        }
        int dragedOrgParentId = dragedOrg.getParentId();
        // 防止父节点被拖到子节点上
        if (targetParentOrg != null && targetParentOrg.getLongCode().startsWith(dragedOrg.getLongCode() + START_SPLIT)) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_ORG_PARENTNODE_DRAG_TO_SUBNODE);
        }
        // targetPreId的组织必须在targetParentId的组织下
        Org targetPreOrg = null;
        if (targetPreId != 0) {
            targetPreOrg = (Org) dao.findForObject("OrgMapper.findById", targetPreId);
            if (targetParentOrg != null) {
                if (targetPreOrg == null || !targetPreOrg.getParentId().equals(targetParentOrg.getId())) {
                    throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NOT_FOUND, targetPreId);
                }
            }
        }

        // 被拖动层的所有下层节点
        List<Org> dragedSubNodes = getAllSubOrgsByLongCode(orgGroupId, dragedOrg.getLongCode());

        // 修改拖动节点的父节点id 层级level 长编码
        if (targetParentOrg != null) {
            dragedOrg.setParentId(targetParentOrg.getId());
            dragedOrg.setLevel(targetParentOrg.getLevel() + 1);
            dragedOrg.setLongCode(targetParentOrg.getLongCode() + "##" + dragedOrg.getCode());
        } else {
            dragedOrg.setParentId(0);
            dragedOrg.setLevel(1);
            dragedOrg.setLongCode(dragedOrg.getCode());
        }
        // 目标层的子节点
        List<Org> targetLevelOrgs;
        if (targetParentOrg != null) {
            targetLevelOrgs = getSubOrgs(orgGroupId, targetParentOrg.getId());
        } else {
            targetLevelOrgs = getSubOrgs(orgGroupId, 0);
        }
        // 如果是同层的元素，先删除
        for (int index = targetLevelOrgs.size() - 1; index >= 0; index--) {
            if (targetLevelOrgs.get(index).getId().equals(dragedOrg.getId())) {
                targetLevelOrgs.remove(index);
            }
        }

        // 先修改同层元素的orgOrder
        if (targetPreId == 0 || targetLevelOrgs.size() == 0) {
            targetLevelOrgs.add(0, dragedOrg);
        } else {
            int index = 0;
            for (Org org : targetLevelOrgs) {
                index++;
                if (org.getId().equals(targetPreId)) {
                    targetLevelOrgs.add(index, dragedOrg);
                    break;
                }
            }
        }

        int index = 1;
        for (Org org : targetLevelOrgs) {
            org.setOrdinal(index);
            index++;
        }
        // 批量更新本层的组织
        batchUpdateOrg(targetLevelOrgs);

        // 处理拖动子层的节点
        Map<String, Org> orgMap = new HashMap<>();
        orgMap.put(dragedOrg.getId() + "", dragedOrg);
        if (dragedSubNodes.size() > 0) {
            for (Org org : dragedSubNodes) {
                Org parentOrg = orgMap.get(org.getParentId() + "");
                // 只会有长编码和层级发生变化
                org.setLongCode(parentOrg.getLongCode() + "##" + org.getCode());
                org.setLevel(parentOrg.getLevel() + 1);
                orgMap.put(org.getId() + "", org);
                if (org.getLevel() > 5) {
                    throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_ORG_LEVEL_TOODEEP);
                }
            }
            // 批量更新拖动节点所有的子节点
            batchUpdateOrg(dragedSubNodes);
        }
        if (targetParentOrg != null) {
            targetParentOrg.setIsLeaf(false);
            dao.update("OrgMapper.update", targetParentOrg);
        }

        // 检查父级节点是否isleaf 被拖走节点的父节点可能再无子节点
        checkParentLeaf(orgGroupId, dragedOrgParentId);
        // 再检查拖动完之后的名称是否有重复
        try {
            checkOrgExist(dragedOrg);
        } catch (BizException e) {
            if (orgGroupId == ORG_DRAG_NAME_REPEAT) {
                throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_ORG_DRAG_NAMEREPEAT_ERR);
            }
            if (orgGroupId == USER_GROUP_DRAG_NAMEREPEAT) {
                throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_USERGROUP_DRAG_NAMEREPEAT_ERR);
            }
        }
        String orgGroup;
        if (orgGroupId == GROUP) {
            orgGroup = "用户组";
        } else {
            orgGroup = "组织";
        }
        String parentOrgName = "";
        if (targetParentOrg != null) {
            parentOrgName = targetParentOrg.getName();
        }
        String targetPreOrgName = "";
        if (targetPreOrg != null) {
            targetPreOrgName = targetPreOrg.getName();
        }
        String log = String.format(new StringBuilder().append("将").append(orgGroup).append("%s%s%s").toString(), orgid + new StringBuilder().append("(").append(dragedOrg.getName()).append(")").toString()
                , new StringBuilder().append("拖动到").append(orgGroup).append(targetParentId).append("(").append(parentOrgName).append(")").toString()
                , new StringBuilder().append("下的").append(orgGroup).append(targetParentId).append("(").append(targetPreOrgName).append(")").append("后面").toString());
        PrincipalLogUtils.addOperationLog(ModuleNames.SYS, ModuleNames.SYS_ORG, UserActions.UPDATE,
                log, null);
    }

    /**
     * 比如要把一个节点B向下移动 参数分别为 orgGroupId orgid:节点B的Id direct:1
     * <p>
     * <p>
     * <pre>
     * ---+父节点
     *    |-----子节点A
     *    |-----子节点B
     *    |-----子节点C
     * </pre>
     * 移动方向:-1向上移动 1向下移动
     *
     * @see OrgService#shiftOrgTreeNode(int, int, int)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void shiftOrgTreeNode(int orgGroupId, int orgid, int direct) {
        // 被拖动的节点
        Org shiftOrg = (Org) dao.findForObject("OrgMapper.findById", orgid);
        if (shiftOrg == null || orgGroupId != shiftOrg.getOrgGroupId()) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NOT_FOUND,
                    "orgGroupId:" + orgGroupId + "~" + orgid);
        }
        // 被拖动层的所有下层节点
        List<Org> sameLevelNodes = getSubOrgs(orgGroupId, shiftOrg.getParentId());
        int order = shiftOrg.getOrdinal() + direct;
        // 已经移到最下或最上
        if (order == 0 || order == (sameLevelNodes.size() + 1)) {
            return;
        }

        // 如果是同层的元素，先删除
        for (int index = sameLevelNodes.size() - 1; index >= 0; index--) {
            if (sameLevelNodes.get(index).getId().equals(shiftOrg.getId())) {
                sameLevelNodes.remove(index);
            }
        }

        sameLevelNodes.add(order - 1, shiftOrg);
        int index = 1;
        for (Org org : sameLevelNodes) {
            org.setOrdinal(index);
            index++;
        }
        // 批量更新拖动节点所有的子节点
        batchUpdateOrg(sameLevelNodes);
        String log = String.format("将" + (orgGroupId != 2 ? "组织" : "用户组") + "%s%s", orgid, direct == -1 ? "上移" : "下移");
        PrincipalLogUtils.addOperationLog(ModuleNames.SYS, ModuleNames.SYS_ORG, UserActions.UPDATE,
                log, null);
    }

    /**
     * 根据userId查询用户所属部门/用户组
     *
     * @see OrgService#findByUserId(int)
     */
    @Override
    public List<Org> findByUserId(int userId) {
        return dao.findForList("OrgMapper.findByUserId", userId, Org.class);
    }

    /**
     * 根据用户Id查询组织机构 如果用户被删除 则返null
     *
     * @param userId
     * @return
     */
    @Override
    public List<Org> findByUnDeletedUserId(int userId) {
        return dao.findForList("OrgMapper.findByUnDeletedUserId", userId, Org.class);
    }

    /**
     * 根据userId查询用户所属部门/用户组
     *
     * @see OrgService#findOrganizationByUserId(int)
     */
    @Override
    public Org findOrganizationByUserId(int userId) {
        List<Org> orgs = findByUserId(userId);
        if (orgs != null && orgs.size() > 0) {
            for (Org org : orgs) {
                if (org.getOrgGroupId() == 1) {
                    return org;
                }
            }
        }
        return null;
    }

    /**
     * 按组织编码查找组织
     *
     * @see OrgService#findByOrgCode(int,
     * String)
     */
    @Override
    public Org findByOrgCode(int orgGroupId, String orgCode) {
        ParamData pd = new ParamData();
        pd.put("orgGroupId", orgGroupId);
        pd.put("code", orgCode);
        Org org = (Org) dao.findForObject("OrgMapper.findByOrgCode", pd);
        if (org == null || org.getOrgGroupId() != orgGroupId) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_CODE_EXIST,
                    "orgGroupId:" + orgGroupId + "~" + orgCode);
        }
        return org;
    }

    /**
     * 按组织id查找组织
     *
     * @see OrgService#findById(int, int)
     */
    @Override
    public OrgDto findById(int orgGroupId, int orgid) {
        Org org = (Org) dao.findForObject("OrgMapper.findById", orgid);
        if (org == null || org.getOrgGroupId() != orgGroupId) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NOT_FOUND,
                    "orgGroupId:" + orgGroupId + "~" + orgid);
        }
        OrgDto orgDto = new OrgDto();
        BeanUtils.copyProperties(org, orgDto);


        Map<String, Object> map = new HashMap<>();
        map.put("orgGroupId", orgGroupId);
        map.put("array", org.getLongCode().split("##"));
        List<Org> porgs = dao.findForList("OrgMapper.findOrgByOrgCodes", map, Org.class);
        Map<String, Org> porgMap = EntityUtils.getStringKeyMapFromBeans(porgs, "id");

        // 设置父节点
        orgDto.getParentIds().add(org.getId());
        Org porg1 = porgMap.get(org.getParentId() + "");
        while (porg1 != null) {
            orgDto.getParentIds().add(0, porg1.getId());
            porg1 = porgMap.get(porg1.getParentId() + "");
        }

        Org porg = (Org) dao.findForObject("OrgMapper.findById", org.getParentId());
        if (porg != null) {
            orgDto.setParentName(porg.getShortName());
        } else {
            orgDto.setParentName("无");
        }
        return orgDto;
    }

    /**
     * 删除该组织后，该组织下所有子组织、用户、角色也被删除。
     *
     * @see OrgService#deleteOrgTreeNode(int,
     * int)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteOrgTreeNode(int orgGroupId, int orgid) {
        Org org = (Org) dao.findForObject("OrgMapper.findById", orgid);
        if (org == null || org.getOrgGroupId() != orgGroupId) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NOT_FOUND,
                    "orgGroupId:" + orgGroupId + "~" + orgid);
        }
        if (org.getId() == 1) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_ORG_ROOT_NO_DELETE);
        }
        if (org.getIsSystem()) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_ISSYSTEM_NODELETE, "");
        }
        List<Org> subOrgs = getAllSubOrgsByLongCode(orgGroupId, org.getLongCode());
        List<Integer> orgIds = EntityUtils.getIntPropListFromBeans(subOrgs, "id");
        // 防止空报错 设置一个不存在的id
        orgIds.add(Integer.MIN_VALUE);
        // 组织机构 存在有关系的不让删除
        if (orgGroupId == 1) {
            if (!org.getIsLeaf()) {
                throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_ORG_HAS_SUBNODE, org.getId());
            }
            // 有分配用户
            List<OrgUserCountDto> orgUserCountDtos = dao.findForList("UserOrgMapper.queryUserCountByOrgIds", orgIds,
                    OrgUserCountDto.class);
            if (orgUserCountDtos.size() > 0) {
                throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_ORG_HAS_USER, org.getId());
            }
            // 有分配角色
            List<OrgRoleCountDto> orgRoleCountDtos = dao.findForList("OrgRoleMapper.queryRoleCountByOrgIds", orgIds,
                    OrgRoleCountDto.class);
            if (orgRoleCountDtos.size() > 0) {
                throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_ORG_HAS_ROLE, org.getId());
            }

        }
        // 用户组 直接删除用户组关联的用户关系 用户组关联的角色关系 用户组的子组织
        if (orgGroupId == GROUP) {
            orgIds.add(orgid);
            dao.delete("UserOrgMapper.deleteByOrgIds", orgIds);
            dao.delete("OrgRoleMapper.deleteByOrgIds", orgIds);
            dao.update("OrgMapper.deleteByIds", orgIds);
        }
        dao.update("OrgMapper.deleteById", orgid);
        // 检查父级节点是否isleaf
        checkParentLeaf(orgGroupId, org.getParentId());
        Map<String, Object> dataBackup = new HashedMap();
        dataBackup.put("DELETE_SYS_ORG", orgid);
        String log = String.format((orgGroupId != 2 ? "删除组织" : "删除用户组"));
        PrincipalLogUtils.addOperationLog(ModuleNames.SYS, ModuleNames.SYS_ORG, UserActions.DELETE,
                log, dataBackup);
    }

    /**
     * @param orgGroupId orgGroupId
     * @param porgId     porgId
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void checkParentLeaf(int orgGroupId, int porgId) {
        // 检查其父节点是否为leaf
        Org porg = (Org) dao.findForObject("OrgMapper.findById", porgId);
        if (porg != null) {
            List<Org> pOrgs = getAllSubOrgsByLongCode(orgGroupId, porg.getLongCode());
            if (pOrgs.size() == 0) {
                porg.setIsLeaf(true);
                dao.update("OrgMapper.update", porg);
            }
        }

    }

    /**
     * 给组织分配角色
     *
     * @see OrgService#assignOrgRoles(int, int,
     * java.lang.String)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void assignOrgRoles(int orgGroupId, int orgId, String roleIds) {
        Org org = (Org) dao.findForObject("OrgMapper.findById", orgId);
        if (org == null || org.getOrgGroupId() != orgGroupId) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NOT_FOUND,
                    "orgGroupId:" + orgGroupId + "~" + orgId);
        }

        // 先把所有的已分配的角色删除
        dao.delete("OrgRoleMapper.deleteByOrgId", orgId);

        // 再分配角色
        String[] roles = roleIds.split(",");
        if (roles.length == 0) {
            return;
        }
        List<OrgRole> orgRoleList = new ArrayList<>();
        for (String roleId : roles) {
            OrgRole ur = new OrgRole();
            ur.setRoleId(Integer.parseInt(roleId));
            ur.setOrgId(orgId);
            orgRoleList.add(ur);
        }
        dao.batchInsert("OrgRoleMapper.insert", orgRoleList);
        String log = String.format("给" + (orgGroupId != 2 ? "组织" : "用户组") + "%s%s%s", orgId, "分配角色", roleIds);
        PrincipalLogUtils.addOperationLog(ModuleNames.SYS, ModuleNames.SYS_ORG, UserActions.UPDATE,
                log, null);
    }

    /**
     * 移除组织分配的角色
     *
     * @see UserService#removeUserRole(int, int)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void removeOrgRole(int orgGroupId, int orgId, int roleId) {
        Org org = (Org) dao.findForObject("OrgMapper.findById", orgId);
        if (org == null || org.getOrgGroupId() != orgGroupId) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NOT_FOUND,
                    "orgGroupId:" + orgGroupId + "~" + orgId);
        }


        List<OrgRole> ors = dao.findForList("OrgRoleMapper.findByOrgId", orgId, OrgRole.class);
        // 待移除角色id
        List<Integer> deleted = new ArrayList<>();
        for (OrgRole ur : ors) {
            if (ur.getRoleId() == roleId) {
                deleted.add(ur.getId());
                break;
            }
        }
        if (deleted.size() == 0) {
            return;
        }
        dao.delete("OrgRoleMapper.deleteById", deleted.get(0));
        String log = String.format("移除" + (orgGroupId != 2 ? "组织" : "用户组") + "%s%s%s", orgId, "分配的角色", roleId);
        PrincipalLogUtils.addOperationLog(ModuleNames.SYS, ModuleNames.SYS_ORG, UserActions.UPDATE,
                log, null);
    }

    /**
     * 给用户组分配用户
     *
     * @see OrgService#assignOrgUsers(int, int, List)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void assignOrgUsers(int orgGroupId, int orgid, List<Integer> users) {
        //只允许用户组操作
        if (orgGroupId != GROUP ) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_ARGUMENT_ILLEGAL,
                    "orgGroupId:" + orgGroupId);
        }
        Org org = (Org) dao.findForObject("OrgMapper.findById", orgid);
        if (org == null || org.getOrgGroupId() != orgGroupId) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_MODEL_NOT_FOUND,
                    "orgGroupId:" + orgGroupId + "~" + orgid);
        }
        //先删除这个用户组所有的用户
        dao.delete("UserOrgMapper.deleteByOrgId", orgid);
        if (users.size() == 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        List<UserOrg> addedUserOrg = new ArrayList<>();
        for (Integer userId : users) {
            if (map.get(userId + "") == null) {
                UserOrg uo = new UserOrg();
                uo.setOrgId(orgid);
                uo.setUserId(userId);
                addedUserOrg.add(uo);
                map.put(userId + "", userId + "");
            }
        }
        dao.batchInsert("UserOrgMapper.insert", addedUserOrg);
        String log = String.format(new StringBuilder().append("给").append("用户组").append("%s%s%s").toString(), orgid, "分配用户", users);
        PrincipalLogUtils.addOperationLog(ModuleNames.SYS, ModuleNames.SYS_ORG, UserActions.UPDATE,
                log, null);
    }

    /**
     * 删除用户组中的用户
     *
     * @see OrgService#removeOrgUsers(int, List)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void removeOrgUsers(int orgGroupId, List<UserOrgRelDto> userOrgs) {
        //只允许用户组操作
        if (orgGroupId != GROUP) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_ARGUMENT_ILLEGAL,
                    "orgGroupId:" + orgGroupId);
        }

        if (userOrgs == null || userOrgs.size() == 0) {
            throw Exceptions.bizException(SysErrorCodes.ERROR_ARGUMENT_EMPTY);
        }
        for (UserOrgRelDto uo : userOrgs) {

            Map<String, Object> map = new HashMap<>();
            map.put("orgId", uo.getOrgId());
            map.put("userId", uo.getUserId());
            dao.delete("UserOrgMapper.deleteByOrgAndUserId", map);
        }
        //保存操作日志
        String log = String.format(new StringBuilder().append("移除").append("用户组").append("%s%s").toString(), orgGroupId, "分配的用户");
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SYS_ORG", userOrgs);
        PrincipalLogUtils.addOperationLog(ModuleNames.SYS, ModuleNames.SYS_ORG, UserActions.UPDATE, log, dataBackup);
    }

    /**
     * i18N相关的操作  start
     */
    @Autowired
    protected I18nMessages messageSource;

    /**
     * @param moduleKey -- module key
     * @return module 字符
     */
    private String[] getModuleName(String moduleKey) {
        String[] moduleNames = null;
        if (org.springframework.util.StringUtils.hasLength(moduleKey)) {
            String moduleName = messageSource.getMessage(moduleKey, null);
            moduleNames = new String[]{moduleName};
        }
        return moduleNames;
    }

    /**
     * 根据用户userId获取所有的组织机构和用户分组列表
     *
     * @param userId
     * @return
     */

    @Override
    public List<Integer> getOrgByUserId(int userId) {
        List<Integer> orgIdList = new ArrayList<Integer>();
        // 根据userId查询用户所属组织机构和用户分组
        List<Org> orgList = dao.findForList("OrgMapper.findByUserId", userId, Org.class);
        if (orgList != null && orgList.size() > 0) {
            // 遍历所有组织机构和用户分组
            for (Org org : orgList) {
                // 根据##将orgLongCode分成orgCode
                String[] orgCode = org.getLongCode().split(REGEX);
                // 将组织机构或者用户分组的叶子节点添加到orgIdList（部门Id列表）
                orgIdList.add(org.getId());
                if (orgCode != null && orgCode.length > 0) {
                    // 遍历所有orgCode
                    for (String strCode : orgCode) {
                        ParamData pd = new ParamData();
                        pd.put("orgGroupId", org.getOrgGroupId());
                        pd.put("code", strCode);
                        // 根据用户分组标识和orgCode查找组织机构
                        Org orgParent = (Org) dao.findForObject("OrgMapper.findByOrgCode", pd);
                        orgIdList.add(orgParent.getId());
                    }
                }
            }
        }
        return orgIdList;
    }

    /**
     * 根据orgId获取所有父级orgCode
     *
     * @param orgId
     * @return
     */
    @Override
    public String[] getOrgParentByOrgId(int orgId) {
        // 根据部门id查找部门
        Org org = (Org) dao.findForObject("OrgMapper.findById", orgId);
        // longCode
        if(org!=null){
        	 String longCode = org.getLongCode();
             // 将longCode用"##"分割成OrgCode
             String[] codeArry = longCode.split("##");
             return codeArry;
        }
        else{
        	return null;
        }
       
    }

    /**
     * 给指定的角色全量分配成员，必须删除之前关系表中的关系
     *
     * @param roleId
     * @param members
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void assignRoleMembers(int roleId, List<RoleMembership> members) {
        dao.delete("OrgRoleMapper.deleteByRoleId", roleId);
        if (members == null || members.size() == 0) {
            return;
        }
        //因为查询接受用户类型的 所以这里要把用户的处理掉
        List<RoleMembership> accepted = new ArrayList<>();
        for (int index = members.size() - 1; index >= 0; index--) {
            if (isMembershipDataAcceptable(members.get(index))) {
                accepted.add(members.get(index));
            }
        }
        if (accepted.size() == 0) {
            return;
        }
        List<OrgRole> addedOrgRole = new ArrayList<>();

        for (RoleMembership member : accepted) {
            OrgRole or = new OrgRole();
            or.setOrgId(member.getIdAsInteger());
            or.setRoleId(roleId);
            addedOrgRole.add(or);
        }

        dao.batchInsert("OrgRoleMapper.insert", addedOrgRole);
    }

    /**
     * 删除角色分配的成员
     *
     * @param roleId
     * @param members
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void removeRoleMembers(int roleId, List<RoleMembership> members) {
        // 直接按角色id和组织id列表删除
        if (members == null || members.size() == 0) {
            return;
        }
        //因为查询接受用户类型的 所以这里要把用户的处理掉
        List<RoleMembership> accepted = new ArrayList<>();
        for (int index = members.size() - 1; index >= 0; index--) {
            if (isMembershipDataAcceptable(members.get(index))) {
                accepted.add(members.get(index));
            }
        }

        if (accepted.size() == 0) {
            return;
        }
        List<Integer> memberIds = new ArrayList<>();
        accepted.forEach(member -> {
            if (member.getIdAsInteger() > 0) {
                memberIds.add(member.getIdAsInteger());
            } else {
                throw Exceptions.bizException(SysErrorCodes.ERROR_ARGUMENT_EMPTY, "null orgId");
            }
        });

        Map<String, Object> param = new HashMap<>();
        param.put("roleId", roleId);
        param.put("list", memberIds);
        dao.delete("OrgRoleMapper.deleteByRoleIdAndOrgIds", param);
    }

    @Override
    public String getMembershipTypeName() {
        return MEMBERSHIP_TYPE_NAME;
    }

    @Override
    public boolean isMembershipAcceptable(RoleMembership membership) {
        return membership != null
                && (MembershipType.ORGANIZATION.equals(membership.getMembershipType())
                || MembershipType.USER_GROUP.equals(membership.getMembershipType())
                /*|| MembershipType.USER.equals(membership.getMembershipType())*/
        );
    }

    public boolean isMembershipDataAcceptable(RoleMembership membership) {
        return membership != null
                && (MembershipType.ORGANIZATION.equals(membership.getMembershipType())
                || MembershipType.USER_GROUP.equals(membership.getMembershipType())
        );
    }

    @Override
    public List<Role> getRolesByMember(RoleMembership member) {

        if (!isMembershipAcceptable(member)) {
            return null;
        }

        //将组织以及组织所有的父节点的id提取出来
        Org org = (Org) dao.findForObject("OrgMapper.findById", member.getIdAsInteger());
        if (org == null) {
            return null;
        }
        String[] orgCodes = org.getLongCode().split(REGEX);
        ParamData pd = new ParamData();
        pd.put("array", orgCodes);
        pd.put("orgGroupId", member.getMembershipType().getValue() == MembershipType.ORGANIZATION.getValue() ? 1 : 2);
        List<Org> orgParent = dao.findForList("OrgMapper.findOrgByOrgCodes", pd, Org.class);

        List<Integer> orgIdList = new ArrayList<>();
        orgIdList.add(org.getId());
        if (orgParent != null && orgParent.size() > 0) {
            orgIdList.addAll(EntityUtils.getIntPropListFromBeans(orgParent, "id"));
        }
        // 根据组织机构OrgIds批量查询角色
        List<Role> roleByOrg = dao.findForList("OrgRoleMapper.findRolesByOrgIds", orgIdList, Role.class);
        return roleByOrg;
    }
    
    @Override
    public Org findById(int id){
    	 Org org = (Org) dao.findForObject("OrgMapper.findById", id);
    	 return org;
    }

}
